<template>
  <div class="trend-analysis" v-loading="loading">
    <el-row :gutter="20">
      <!-- 趋势分析概览 -->
      <el-col :span="24">
        <el-card shadow="hover" class="trend-card">
          <div slot="header" class="card-header">
            <span>质量趋势分析</span>
            <el-button type="primary" size="small" @click="exportTrend" :disabled="!hasData">
              <i class="el-icon-download"></i> 导出报告
            </el-button>
          </div>
          <!-- 趋势图表 -->
          <div class="chart-container" ref="trendChart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 趋势异常和预测 -->
    <el-row :gutter="20" class="trend-row">
      <el-col :xs="24" :sm="12" :md="12">
        <el-card shadow="hover" class="anomaly-card">
          <div slot="header" class="card-header">
            <span>异常点检测</span>
          </div>
          <div v-if="hasAnomalies" class="anomaly-content">
            <el-table :data="trendData.anomalies" style="width: 100%">
              <el-table-column prop="date" label="日期"></el-table-column>
              <el-table-column prop="value" label="测量值"></el-table-column>
              <el-table-column prop="type" label="异常类型">
                <template slot-scope="scope">
                  <el-tag :type="getAnomalyTagType(scope.row.type)">{{ scope.row.type }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="异常说明"></el-table-column>
            </el-table>
          </div>
          <div v-else class="empty-data">
            <el-empty description="暂无检测到异常点"></el-empty>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="12">
        <el-card shadow="hover" class="prediction-card">
          <div slot="header" class="card-header">
            <span>趋势预测</span>
          </div>
          <div v-if="hasPrediction" class="prediction-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="statistic-item">
                  <div class="item-title">短期趋势</div>
                  <div class="item-value" :class="getShortTermTrendClass">
                    {{ getShortTermTrend }}
                  </div>
                  <div class="item-desc">未来7天的预期趋势</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="statistic-item">
                  <div class="item-title">长期趋势</div>
                  <div class="item-value" :class="getLongTermTrendClass">
                    {{ getLongTermTrend }}
                  </div>
                  <div class="item-desc">未来30天的预期趋势</div>
                </div>
              </el-col>
            </el-row>
            
            <el-divider></el-divider>
            
            <div class="prediction-details">
              <h4>预测信息</h4>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="预测周期">{{ trendData.prediction.period || '--' }}</el-descriptions-item>
                <el-descriptions-item label="预测精度">{{ trendData.prediction.accuracy || '--' }}</el-descriptions-item>
                <el-descriptions-item label="预测方法">{{ trendData.prediction.method || '--' }}</el-descriptions-item>
                <el-descriptions-item label="最佳预期值">{{ trendData.prediction.bestEstimate || '--' }}</el-descriptions-item>
                <el-descriptions-item label="可能范围">{{ trendData.prediction.range ? trendData.prediction.range.join(' ~ ') : '--' }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
          <div v-else class="empty-data">
            <el-empty description="需要足够的历史数据进行预测"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 季节性分析 -->
    <el-row :gutter="20" class="trend-row">
      <el-col :span="24">
        <el-card shadow="hover" class="seasonal-card">
          <div slot="header" class="card-header">
            <span>周期性分析</span>
          </div>
          <div v-if="hasSeasonality" class="chart-container" ref="seasonalChart"></div>
          <div v-else class="empty-data">
            <el-empty description="需要足够的历史数据进行周期性分析"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 改进建议 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>趋势解读与改进建议</span>
          </div>
          <div class="interpretation-content">
            <el-alert
              :title="getTrendAlert.title"
              :type="getTrendAlert.type"
              :description="getTrendAlert.description"
              show-icon
              :closable="false">
            </el-alert>
            
            <div class="suggestions-section" v-if="hasSuggestions">
              <h4>改进建议:</h4>
              <el-divider></el-divider>
              <el-timeline>
                <el-timeline-item 
                  v-for="(suggestion, index) in trendData.suggestions" 
                  :key="index"
                  :type="suggestion.priority === 'high' ? 'danger' : suggestion.priority === 'medium' ? 'warning' : 'success'"
                  :timestamp="suggestion.category">
                  {{ suggestion.content }}
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: "TrendAnalysis",
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    queryParams: {
      type: Object,
      required: true
    },
    trendData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      trendChart: null,
      seasonalChart: null
    }
  },
  computed: {
    hasData() {
      return this.trendData.trendData && this.trendData.trendData.length > 0;
    },
    hasAnomalies() {
      return this.trendData.anomalies && this.trendData.anomalies.length > 0;
    },
    hasPrediction() {
      return this.trendData.prediction && Object.keys(this.trendData.prediction).length > 0;
    },
    hasSeasonality() {
      return this.trendData.seasonality && this.trendData.seasonality.length > 0;
    },
    hasSuggestions() {
      return this.trendData.suggestions && this.trendData.suggestions.length > 0;
    },
    getShortTermTrend() {
      if (!this.hasPrediction) return 'N/A';
      
      const trend = this.trendData.prediction.shortTermTrend || '';
      const trendMap = {
        'increasing': '上升',
        'stable': '稳定',
        'decreasing': '下降',
        'unstable': '不稳定'
      };
      
      return trendMap[trend] || trend;
    },
    getLongTermTrend() {
      if (!this.hasPrediction) return 'N/A';
      
      const trend = this.trendData.prediction.longTermTrend || '';
      const trendMap = {
        'increasing': '上升',
        'stable': '稳定',
        'decreasing': '下降',
        'unstable': '不稳定'
      };
      
      return trendMap[trend] || trend;
    },
    getShortTermTrendClass() {
      if (!this.hasPrediction) return '';
      
      const trend = this.trendData.prediction.shortTermTrend || '';
      switch (trend) {
        case 'increasing': return this.isQualityMetric ? 'text-excellent' : 'text-poor';
        case 'stable': return 'text-good';
        case 'decreasing': return this.isQualityMetric ? 'text-poor' : 'text-excellent';
        default: return 'text-warning';
      }
    },
    getLongTermTrendClass() {
      if (!this.hasPrediction) return '';
      
      const trend = this.trendData.prediction.longTermTrend || '';
      switch (trend) {
        case 'increasing': return this.isQualityMetric ? 'text-excellent' : 'text-poor';
        case 'stable': return 'text-good';
        case 'decreasing': return this.isQualityMetric ? 'text-poor' : 'text-excellent';
        default: return 'text-warning';
      }
    },
    // 判断是否为质量指标（合格率等，增加是好的；如果是缺陷数，增加是坏的）
    isQualityMetric() {
      const paramName = this.queryParams.paramName || '';
      return paramName.includes('合格率') || paramName.includes('良品率');
    },
    getTrendAlert() {
      if (!this.hasData) {
        return {
          title: '没有数据',
          type: 'info',
          description: '请选择产品、批次和参数，并设置时间范围进行查询。'
        };
      }
      
      if (this.hasAnomalies && this.trendData.anomalies.length > 3) {
        return {
          title: '存在多个异常点',
          type: 'error',
          description: '检测到多个异常点，表明过程可能存在系统性问题。建议检查设备校准、操作流程和材料质量。'
        };
      } else if (this.hasAnomalies) {
        return {
          title: '检测到异常点',
          type: 'warning',
          description: '检测到少量异常点，可能是随机因素或特殊原因导致。建议关注这些点的发生情况。'
        };
      }
      
      if (this.hasPrediction) {
        const shortTrend = this.trendData.prediction.shortTermTrend;
        const longTrend = this.trendData.prediction.longTermTrend;
        
        if ((this.isQualityMetric && shortTrend === 'increasing') ||
            (!this.isQualityMetric && shortTrend === 'decreasing')) {
          return {
            title: '趋势向好',
            type: 'success',
            description: '当前质量趋势向好，预计将继续改善。建议维持现有工艺参数和控制方法。'
          };
        } else if ((this.isQualityMetric && shortTrend === 'decreasing') ||
                  (!this.isQualityMetric && shortTrend === 'increasing')) {
          return {
            title: '趋势恶化',
            type: 'error',
            description: '质量指标趋势恶化，需关注工艺参数变化、设备状态和操作人员培训等因素。'
          };
        } else if (shortTrend === 'stable') {
          return {
            title: '趋势稳定',
            type: 'success',
            description: '质量指标趋势稳定，过程处于受控状态。可考虑优化工艺参数以进一步提高质量水平。'
          };
        }
      }
      
      return {
        title: '趋势分析',
        type: 'info',
        description: '基于历史数据的趋势分析可帮助预测未来质量状况，及早发现潜在问题。'
      };
    }
  },
  watch: {
    'trendData': {
      handler() {
        this.$nextTick(() => {
          this.initCharts();
        });
      },
      deep: true
    },
    'loading': {
      handler(newVal) {
        if (!newVal) {
          this.$nextTick(() => {
            this.initCharts();
          });
        }
      }
    }
  },
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    this.disposeCharts();
  },
  methods: {
    getAnomalyTagType(type) {
      const typesMap = {
        'outlier': 'danger',
        'shift': 'warning',
        'trend': 'warning',
        'cycle': 'info',
        'spike': 'danger'
      };
      return typesMap[type] || 'info';
    },
    resizeCharts() {
      this.trendChart?.resize();
      this.seasonalChart?.resize();
    },
    disposeCharts() {
      this.trendChart?.dispose();
      this.seasonalChart?.dispose();
    },
    initCharts() {
      this.initTrendChart();
      this.initSeasonalChart();
    },
    initTrendChart() {
      if (!this.$refs.trendChart) return;
      
      if (this.trendChart) {
        this.trendChart.dispose();
      }
      
      this.trendChart = echarts.init(this.$refs.trendChart);
      
      const trendData = this.trendData.trendData || [];
      if (trendData.length === 0) {
        // 如果没有数据，添加模拟数据
        this.generateMockData();
        return;
      }
      
      const dates = trendData.map(item => item.date);
      const values = trendData.map(item => item.value);
      const usl = trendData[0]?.usl;
      const lsl = trendData[0]?.lsl;
      const target = trendData[0]?.target;
      
      // 异常点数据
      const anomalies = this.trendData.anomalies || [];
      const anomalyData = anomalies.map(item => {
        const index = dates.indexOf(item.date);
        return index >= 0 ? [index, values[index]] : [];
      }).filter(item => item.length > 0);
      
      // 预测数据
      let predictionDates = [];
      let predictionValues = [];
      let predictionUpper = [];
      let predictionLower = [];
      
      if (this.trendData.prediction && this.trendData.prediction.dates) {
        predictionDates = this.trendData.prediction.dates || [];
        predictionValues = this.trendData.prediction.values || [];
        predictionUpper = this.trendData.prediction.upper || [];
        predictionLower = this.trendData.prediction.lower || [];
      } else {
        // 如果没有预测数据，生成模拟预测数据
        const lastDate = new Date(dates[dates.length - 1]);
        const lastValue = values[values.length - 1];
        
        for (let i = 1; i <= 5; i++) {
          const nextDate = new Date(lastDate);
          nextDate.setDate(nextDate.getDate() + (i * 7));
          const dateStr = nextDate.toISOString().split('T')[0];
          
          // 简单线性预测
          const predictedValue = lastValue + (i * 0.1);
          
          predictionDates.push(dateStr);
          predictionValues.push(parseFloat(predictedValue.toFixed(1)));
          predictionUpper.push(parseFloat((predictedValue + 0.5).toFixed(1)));
          predictionLower.push(parseFloat((predictedValue - 0.5).toFixed(1)));
        }
      }
      
      // 合并所有日期，保持唯一性和排序
      const allDates = [...new Set([...dates, ...predictionDates])].sort();
      
      const option = {
        title: {
          text: '测量参数趋势分析',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter: function(params) {
            let result = params[0].axisValue + '<br/>';
            
            params.forEach(param => {
              const marker = param.marker;
              const seriesName = param.seriesName;
              const value = param.value;
              
              if (seriesName !== '异常点' || value !== '-') {
                result += marker + seriesName + ': ' + value + '<br/>';
              }
            });
            
            return result;
          }
        },
        legend: {
          data: ['历史数据', '预测数据', '预测上限', '预测下限', '异常点'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: allDates
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: [
          {
            name: '历史数据',
            type: 'line',
            data: this.mapDataToAllDates(dates, values, allDates),
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              color: '#5470c6'
            },
            markLine: {
              silent: true,
              lineStyle: {
                color: '#333'
              },
              data: [
                ...(usl ? [{ yAxis: usl, name: 'USL', lineStyle: { color: '#f56c6c' } }] : []),
                ...(lsl ? [{ yAxis: lsl, name: 'LSL', lineStyle: { color: '#f56c6c' } }] : []),
                ...(target ? [{ yAxis: target, name: '目标值', lineStyle: { color: '#67c23a' } }] : [])
              ]
            }
          },
          {
            name: '预测数据',
            type: 'line',
            data: this.mapDataToAllDates(predictionDates, predictionValues, allDates),
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              type: 'dashed'
            },
            itemStyle: {
              color: '#91cc75'
            }
          },
          {
            name: '预测上限',
            type: 'line',
            data: this.mapDataToAllDates(predictionDates, predictionUpper, allDates),
            symbol: 'none',
            lineStyle: {
              width: 1,
              type: 'dashed',
              color: '#fac858'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(250, 200, 88, 0.3)' },
                { offset: 1, color: 'rgba(250, 200, 88, 0.1)' }
              ])
            }
          },
          {
            name: '预测下限',
            type: 'line',
            data: this.mapDataToAllDates(predictionDates, predictionLower, allDates),
            symbol: 'none',
            lineStyle: {
              width: 1,
              type: 'dashed',
              color: '#fac858'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(250, 200, 88, 0.1)' },
                { offset: 1, color: 'rgba(250, 200, 88, 0.3)' }
              ])
            }
          },
          {
            name: '异常点',
            type: 'scatter',
            data: anomalyData,
            symbol: 'pin',
            symbolSize: 16,
            itemStyle: {
              color: '#ee6666'
            },
            z: 10
          }
        ]
      };
      
      this.trendChart.setOption(option);
    },
    initSeasonalChart() {
      if (!this.$refs.seasonalChart || !this.hasSeasonality) return;
      
      if (this.seasonalChart) {
        this.seasonalChart.dispose();
      }
      
      this.seasonalChart = echarts.init(this.$refs.seasonalChart);
      
      const seasonality = this.trendData.seasonality || [];
      const periods = seasonality.map(item => item.period);
      const values = seasonality.map(item => item.value);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: periods,
          name: '周期',
          nameLocation: 'middle',
          nameGap: 30
        },
        yAxis: {
          type: 'value',
          name: '强度',
          nameRotate: 90,
          nameLocation: 'middle',
          nameGap: 50
        },
        series: [
          {
            name: '周期强度',
            type: 'bar',
            data: values,
            barWidth: '60%',
            itemStyle: {
              color: function(params) {
                // 根据值的大小生成不同的颜色
                const value = params.data;
                if (value > 0.7) return '#F56C6C';
                if (value > 0.4) return '#E6A23C';
                return '#409EFF';
              }
            }
          }
        ]
      };
      
      this.seasonalChart.setOption(option);
    },
    exportTrend() {
      // 导出图表为图片或PDF
      this.$message({
        message: '报告导出功能开发中...',
        type: 'info'
      });
    },
    // 将数据映射到所有日期上，缺失的为 '-'
    mapDataToAllDates(sourceDates, sourceValues, allDates) {
      return allDates.map(date => {
        const index = sourceDates.indexOf(date);
        return index >= 0 ? sourceValues[index] : '-';
      });
    },
    // 生成模拟数据
    generateMockData() {
      if (this.trendChart) {
        const baseDate = new Date('2024-01-01');
        const dates = [];
        const values = [];
        const anomalies = [];
        
        // 生成历史数据
        for (let i = 0; i < 30; i++) {
          const date = new Date(baseDate);
          date.setDate(date.getDate() + (i * 7));
          const dateStr = date.toISOString().split('T')[0];
          
          let value = 100 + Math.sin(i * 0.5) * 1.5 + i * 0.02;
          
          // 添加一些随机噪声
          value += (Math.random() - 0.5) * 0.8;
          
          // 添加几个异常点
          if (i === 8) {
            value += 2.5;
            anomalies.push({ x: i, y: value });
          }
          if (i === 18) {
            value -= 2.2;
            anomalies.push({ x: i, y: value });
          }
          
          value = parseFloat(value.toFixed(1));
          dates.push(dateStr);
          values.push(value);
        }
        
        // 生成预测数据
        const predictionDates = [];
        const predictionValues = [];
        const predictionUpper = [];
        const predictionLower = [];
        
        for (let i = 1; i <= 5; i++) {
          const lastDate = new Date(dates[dates.length - 1]);
          const nextDate = new Date(lastDate);
          nextDate.setDate(nextDate.getDate() + (i * 7));
          const dateStr = nextDate.toISOString().split('T')[0];
          
          const lastValue = values[values.length - 1];
          const predictedValue = lastValue + (i * 0.1);
          
          predictionDates.push(dateStr);
          predictionValues.push(parseFloat(predictedValue.toFixed(1)));
          predictionUpper.push(parseFloat((predictedValue + 0.5).toFixed(1)));
          predictionLower.push(parseFloat((predictedValue - 0.5).toFixed(1)));
        }
        
        // 合并所有日期
        const allDates = [...dates, ...predictionDates];
        
        // 异常点数据
        const anomalyData = anomalies.map(item => [item.x, item.y]);
        
        const option = {
          title: {
            text: '测量参数趋势分析',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            }
          },
          legend: {
            data: ['历史数据', '预测数据', '预测上限', '预测下限', '异常点'],
            top: 30
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: allDates
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '{value}'
            }
          },
          series: [
            {
              name: '历史数据',
              type: 'line',
              data: this.mapDataToAllDates(dates, values, allDates),
              symbol: 'circle',
              symbolSize: 6,
              itemStyle: {
                color: '#5470c6'
              },
              markLine: {
                silent: true,
                lineStyle: {
                  color: '#333'
                },
                data: [
                  { yAxis: 102, name: 'USL', lineStyle: { color: '#f56c6c' } },
                  { yAxis: 98, name: 'LSL', lineStyle: { color: '#f56c6c' } },
                  { yAxis: 100, name: '目标值', lineStyle: { color: '#67c23a' } }
                ]
              }
            },
            {
              name: '预测数据',
              type: 'line',
              data: this.mapDataToAllDates(predictionDates, predictionValues, allDates),
              symbol: 'circle',
              symbolSize: 6,
              lineStyle: {
                type: 'dashed'
              },
              itemStyle: {
                color: '#91cc75'
              }
            },
            {
              name: '预测上限',
              type: 'line',
              data: this.mapDataToAllDates(predictionDates, predictionUpper, allDates),
              symbol: 'none',
              lineStyle: {
                width: 1,
                type: 'dashed',
                color: '#fac858'
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(250, 200, 88, 0.3)' },
                  { offset: 1, color: 'rgba(250, 200, 88, 0.1)' }
                ])
              }
            },
            {
              name: '预测下限',
              type: 'line',
              data: this.mapDataToAllDates(predictionDates, predictionLower, allDates),
              symbol: 'none',
              lineStyle: {
                width: 1,
                type: 'dashed',
                color: '#fac858'
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(250, 200, 88, 0.1)' },
                  { offset: 1, color: 'rgba(250, 200, 88, 0.3)' }
                ])
              }
            },
            {
              name: '异常点',
              type: 'scatter',
              data: anomalyData,
              symbol: 'pin',
              symbolSize: 16,
              itemStyle: {
                color: '#ee6666'
              },
              z: 10
            }
          ]
        };
        
        this.trendChart.setOption(option);
      }
    }
  }
}
</script>

<style scoped>
.trend-analysis {
  padding: 10px 0;
}
.trend-card {
  margin-bottom: 20px;
}
.trend-row {
  margin-bottom: 20px;
}
.chart-container {
  height: 350px;
  width: 100%;
}
.anomaly-card, .prediction-card, .seasonal-card {
  height: 100%;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.empty-data {
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
.statistic-item {
  text-align: center;
  padding: 10px 0;
}
.item-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}
.item-value {
  font-size: 24px;
  font-weight: bold;
}
.item-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
.text-excellent {
  color: #67c23a;
}
.text-good {
  color: #409EFF;
}
.text-warning {
  color: #e6a23c;
}
.text-poor {
  color: #f56c6c;
}
.prediction-details {
  margin-top: 20px;
}
.interpretation-content {
  padding: 10px;
}
.suggestions-section {
  margin-top: 20px;
}
.anomaly-content, .prediction-content {
  padding: 10px;
}
</style> 